package com.eeepay.eeepay_v2.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.activity.AboutActivity;
import com.eeepay.eeepay_v2.activity.AgentManageActivity;
import com.eeepay.eeepay_v2.activity.ApplyforDevicesActivity;
import com.eeepay.eeepay_v2.activity.CjtInComeActivity;
import com.eeepay.eeepay_v2.activity.DeviceManageActivity;
import com.eeepay.eeepay_v2.activity.NewsCenterActivity;
import com.eeepay.eeepay_v2.activity.PersonManageActivity;
import com.eeepay.eeepay_v2.activity.ProblemHelpActivity;
import com.eeepay.eeepay_v2.activity.PwdActivity;
import com.eeepay.eeepay_v2.activity.ShareBenefitTXActivity;
import com.eeepay.eeepay_v2.activity.SubsidyTXActivity;
import com.eeepay.eeepay_v2.activity.WeekTradeActivity;
import com.eeepay.eeepay_v2.api.AgentAccountBalanceRequestAPI;
import com.eeepay.eeepay_v2.api.CountTerminalApplyRecordAPI;
import com.eeepay.eeepay_v2.api.SubjectNoTypeDef;
import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.MathUtils;
import com.eeepay.eeepay_v2.util.RoleConstantManager;
import com.eeepay.eeepay_v2.util.TimeUtils;
import com.eeepay.v2_library.dialog.CustomDialog;
import com.eeepay.v2_library.dialog.DialogUtil;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshBase;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshScrollView;
import com.eeepay.v2_library.util.ScreenSwitch;
import com.eeepay.v2_library.view.CircleImageView;
import com.eeepay.v2_library.view.HorizontalItemView;
import com.eeepay.v2_library.view.TitleBar;

import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.TransApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TransProto;
import io.grpc.ManagedChannel;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zw on 2016/2/26 0026.
 */
public class FragmentManageCenter extends ABBaseFragment implements View.OnClickListener {
    private final int GET_PROFIT_INFO = 2;//获得分润信息
    private PullToRefreshScrollView scrollView;
    private View view;
    private View line_view;
    private TitleBar titleBar;
    private TextView tv_userName, tv_phone; //tv_agentName;
    private LinearLayout lLayout_manager; //管理员才显示，销售人员不显示
    private LinearLayout rl_subsidiesBalance; //add by zhuangzeqin 2017年6月22日14:21:59 针对一级代理商，有活动补贴账户
    private HorizontalItemView alert_pwd //修改密码
            , problem_back  //问题反馈
            , news_center //消息中心
            , about_us //关于软件
            , hiv_device //add by zhuangzeqin 2017年7月18日09:15:02 新增机具申请入口
            , alert_cjtincome; //add by zhuangzeqin 2017年7月20日09:15:02 新增超级推收益查询入口
    private TextView tv_pos_manage //机具管理
            , tv_agent_manage //代理商管理
            , tv_person_manage;//人员管理
    private LinearLayout rLayout_balance //账户余额
            , rLayout_profit; //今日分润
    //    private View viewVerticalLine;
    private TextView tv_balance, tv_profit, tv_subsidiesBalance;//add by zhuangzeqin 2017年6月22日14:22:15 增加活动账号余额
    private Button btn_exit;
    private Context mContext;
    //    private View v_tipline;
    //add by zhuangzeqin 2017年4月14日13:46:59
    private CircleImageView iv_head;//圆形头像
    //add by zhuangzeqin 2017年5月3日15:27:30 今日分润新增温馨提示语
    private ImageView iv_prompt;
    /**
     * add by zhuangzeqin 2017年6月24日09:25:10 重构抽出一个查询的账号余额的api
     **/
    private AgentAccountBalanceRequestAPI agentAccountBalanceRequestAPI;
    /**
     * add by zhuangzeqin 2017年8月10日14:39:26 待处理的机具申请记录统计
     **/
    private CountTerminalApplyRecordAPI countTerminalApplyRecordAPI;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_manage_center, container, false);
        mContext = getContext();
        /** add by zhuangzeqin 2017年6月24日09:25:10 重构抽出一个查询的账号余额的api **/
        agentAccountBalanceRequestAPI = new AgentAccountBalanceRequestAPI();
        agentAccountBalanceRequestAPI.setResultCallBack(resultCallBack);

        initWidget();
        setWidget();
        return view;
    }

    /**
     * 初始化控件
     */
    private void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        titleBar.setShowLeft(View.GONE);
        titleBar.setTiteTextView("管理中心");
        titleBar.setBackgroundColor(Color.parseColor("#FDFDFD"));
        titleBar.setShowRight(View.VISIBLE);
        titleBar.setRightResource(R.drawable.icon_message);

        scrollView = getViewById(R.id.pull_refresh_scroll_view);
        iv_head = getViewById(R.id.iv_head);
//        v_tipline = getViewById(R.id.v_tipline);
        tv_userName = getViewById(R.id.tv_user_name);
        tv_userName.setText(UserInfo.getUserInfo2SP().getAgentName());
        tv_phone = getViewById(R.id.tv_phone);
        tv_phone.setText(UserInfo.getUserInfo2SP().getPhone());
//        tv_agentName = getViewById(R.id.tv_agent_name);
//        tv_agentName.setText(UserInfo.getUserInfo2SP().getAgentName());
        lLayout_manager = getViewById(R.id.lLayout_manager);
        alert_pwd = getViewById(R.id.alert_pwd);
        problem_back = getViewById(R.id.problem_back);
        news_center = getViewById(R.id.news_center);
        about_us = getViewById(R.id.about_us);
        hiv_device = getViewById(R.id.hiv_device);
        alert_cjtincome = getViewById(R.id.alert_cjtincome);

        tv_pos_manage = getViewById(R.id.pos_manage);
        tv_agent_manage = getViewById(R.id.agent_manage);
        tv_person_manage = getViewById(R.id.person_manage);

        rLayout_balance = getViewById(R.id.rl_balance);
        rLayout_profit = getViewById(R.id.rl_profit);
        tv_balance = getViewById(R.id.tv_balance);
        tv_profit = getViewById(R.id.tv_profit);
        //温馨提示
        iv_prompt = getViewById(R.id.iv_prompt);
        btn_exit = getViewById(R.id.btn_exit);
        if (RoleConstantManager.SALESMAN.equals(UserInfo.getUserInfo2SP().getRole())) {//销售员
            iv_head.setImageResource(R.drawable.home_head_salesman);//add by zhuangzeqin 2017年4月14日13:49:50 显示销售员的头像
            lLayout_manager.setVisibility(View.GONE);
        } else if (RoleConstantManager.MANAGER.equals(UserInfo.getUserInfo2SP().getRole())) {//管理员
            iv_head.setImageResource(R.drawable.home_head_admin);//add by zhuangzeqin 显示管理员的头像
            lLayout_manager.setVisibility(View.VISIBLE);
        }
        //add by zhuangzein 2017年6月22日14:11:10 ，一级代理商才有账户活动补贴
        initOneLevelByAgent();
        /**
         * add by zhuangzeqin 2017年8月10日14:44:57 待处理的机具申请记录统计
         */
        getCountTerminalApplyRecordInfo();
    }

    //add by zhuangzein 2017年6月22日14:11:10 ，一级代理商才有账户活动补贴
    private void initOneLevelByAgent() {
        //发送请求--获取账号余额和今日分润
        agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACCOUNTSUBJECTNO);
        //针对一级代理商，有新增活动补贴账号
        rl_subsidiesBalance = getViewById(R.id.rl_subsidiesBalance);
        tv_subsidiesBalance = getViewById(R.id.tv_subsidiesBalance);//活动补贴(元)
        line_view = getViewById(R.id.line_view);//分割线
        agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACTIVITYSUBJECTNO);
//        if ("1".equals(UserInfo.getUserInfo2SP().getAgentLevel())) {
//            //一级代理商才有活动补贴账户余额
//            rl_subsidiesBalance.setVisibility(View.VISIBLE);
//            line_view.setVisibility(View.VISIBLE);
//            agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACTIVITYSUBJECTNO);
//        } else {
//            line_view.setVisibility(View.GONE);
//            rl_subsidiesBalance.setVisibility(View.GONE);
//        }
    }

    /**
     * 展示待处理的申请数量
     */
    private void initdeviceCount(String count) {
        if (hiv_device != null) {
            if (!count.equals("0")) {
                String rightContent = String.format(getResources().getString(R.string.str_pendingmsg) + "%s", count);
                hiv_device.setRightText(rightContent);
            } else//否则隐藏掉---
            {
                hiv_device.setRightText("");
            }
        }
    }

    /**
     * 账号信息接口回调
     */
    private final AgentAccountBalanceRequestAPI.ResultCallBack resultCallBack = new AgentAccountBalanceRequestAPI.ResultCallBack() {
        @Override
        public void oninit() {
            showProgressDialog();
        }

        @Override
        public void onFail(String msg) {
            showToast(msg);
        }

        @Override
        public void onSucess(String avaliBalance, @SubjectNoTypeDef.SubjectNoType String subjectNoType) {
            if (TextUtils.equals(subjectNoType, SubjectNoTypeDef.ACTIVITYSUBJECTNO))//活动补贴账号
            {
                tv_subsidiesBalance.setText(avaliBalance);
               // NumAnimUtil.startAnim(tv_subsidiesBalance, MathUtils.String2Float(avaliBalance), 1000);//add by zhuangzeqin 2017年7月25日10:44:03 滚动效果
            }
            if (TextUtils.equals(subjectNoType, SubjectNoTypeDef.ACCOUNTSUBJECTNO))//账号余额
            {
                sendHttpRequest(GET_PROFIT_INFO);//获取分润信息
                //add by zhuangzeqin 2017年4月21日10:55:55  根据需求要求，账号余额取值账号系统其它应付款；代理商服务费所对应的可用余额
                tv_balance.setText(avaliBalance);
                //NumAnimUtil.startAnim(tv_balance, MathUtils.String2Float(avaliBalance), 1000);// add by zhuangzeqin 2017年7月25日10:45:33 滚动效果

            }
        }

        @Override
        public void onUnInit() {
            dismissProgressDialog();
            if (scrollView.isRefreshing()) {
                scrollView.onRefreshComplete();
            }
        }
    };

    /**
     * 绑定控件
     */
    private void setWidget() {
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                ScreenSwitch.switchActivity(getContext(), NewsCenterActivity.class, null, 0);
                titleBar.setRightResource(R.drawable.icon_message);
                MyApplication.getInstance().hasNews = false;
            }
        });
        //下拉刷新
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACCOUNTSUBJECTNO);
                //add by zhuangzeqin 2017年8月10日14:44:57 待处理的机具申请记录统计
                getCountTerminalApplyRecordInfo();
                //一级代理商才有活动补贴账户余额
//                if ("1".equals(UserInfo.getUserInfo2SP().getAgentLevel()))
                agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACTIVITYSUBJECTNO);
            }
        });

        alert_pwd.setOnClickListener(this);
        problem_back.setOnClickListener(this);
        news_center.setOnClickListener(this);
        about_us.setOnClickListener(this);
        hiv_device.setOnClickListener(this);
        alert_cjtincome.setOnClickListener(this);

        tv_pos_manage.setOnClickListener(this);
        tv_agent_manage.setOnClickListener(this);
        tv_person_manage.setOnClickListener(this);

        rLayout_balance.setOnClickListener(this);
        rLayout_profit.setOnClickListener(this);
        rl_subsidiesBalance.setOnClickListener(this);//活动账号余额
        btn_exit.setOnClickListener(this);
        iv_prompt.setOnClickListener(this);

    }

    /**
     * 待处理的机具申请记录统计
     */
    private void getCountTerminalApplyRecordInfo() {
        countTerminalApplyRecordAPI = new CountTerminalApplyRecordAPI();
        countTerminalApplyRecordAPI.setResultCallBack(new CountTerminalApplyRecordAPI.ResultCallBack() {
            @Override
            public void onSucess(String Count) {
                initdeviceCount(Count);//从接口获取
            }
        });
        countTerminalApplyRecordAPI.getCountTerminalApplyRecordInfo();
    }

    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        switch (taskId) {
                            case GET_PROFIT_INFO://分润信息
                                TransApiServiceGrpc.TransApiServiceBlockingStub stub1 = TransApiServiceGrpc.newBlockingStub(channel)
                                        .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                                TransProto.ReqTrans request1 = new TransProto.ReqTrans();
                                request1.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                                request1.agentNode = UserInfo.getUserInfo2SP().getAgentNode();
                                request1.transDate = TimeUtils.getNowTime();
                                return stub1.getDayProfit(request1);
                        }
                        return null;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (scrollView.isRefreshing()) {
                            scrollView.onRefreshComplete();
                        }
                        if (result == null) {
                            Toast.makeText(mContext, "查询账户信息失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        switch (taskId) {
                            case GET_PROFIT_INFO://分润信息
                                TransProto.DayProfitRes response1 = (TransProto.DayProfitRes) result;
                                if ("false".equals(response1.resMsg.status)) {
                                    Toast.makeText(mContext, response1.resMsg.msg, Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                tv_profit.setText(MathUtils.String2Float(response1.profitAmount) + "");
//                                NumAnimUtil.startAnim(tv_profit, MathUtils.String2Float(response1.profitAmount), 1000);// add by zhuangzeqin 2017年7月25日10:45:33 滚动效果
                                break;
                        }
                    }
                });
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_profit://今日分润
                Bundle bundle = new Bundle();
                bundle.putString(Constant.INTENT_FLAG, Constant.WEEK_PROFIT);
                ScreenSwitch.switchActivity(mContext, WeekTradeActivity.class, bundle, 0);
                break;
            case R.id.alert_pwd:
                Bundle bundle2 = new Bundle();
                bundle2.putString(Constant.INTENT_FLAG, Constant.MODIFY_PWD);
                ScreenSwitch.switchActivity(mContext, PwdActivity.class, bundle2, 0);
                break;
            case R.id.problem_back:
                ScreenSwitch.switchActivity(mContext, ProblemHelpActivity.class, null, 0);
                break;
            case R.id.news_center:
                ScreenSwitch.switchActivity(mContext, NewsCenterActivity.class, null, 0);
                break;
            case R.id.about_us:
                ScreenSwitch.switchActivity(mContext, AboutActivity.class, null, 0);
                break;
            case R.id.pos_manage:
                ScreenSwitch.switchActivity(mContext, DeviceManageActivity.class, null, 0);
                break;
            case R.id.agent_manage:
                ScreenSwitch.switchActivity(mContext, AgentManageActivity.class, null, 0);
//                showToast("敬请期待");
                break;
            case R.id.person_manage:
                ScreenSwitch.switchActivity(mContext, PersonManageActivity.class, null, 0);
                break;
            case R.id.rl_balance://账户余额
                Intent intent = new Intent(mContext, ShareBenefitTXActivity.class);
                startActivityForResult(intent, Constant.RESULTCODE_100);
//                ScreenSwitch.switchActivity(mContext, ShareBenefitTXActivity.class, null, Constant.RESULTCODE_100);
//                ScreenSwitch.switchActivity(mContext, AccountActivity.class, null, 0);
                break;
            case R.id.rl_subsidiesBalance://add by zhuangzeqin 2017年6月22日14:34:37 活动账号余额 点击事件
                String subsidiesBalance = tv_subsidiesBalance.getText().toString().trim();
                Bundle bundleSubsidies = new Bundle();
                bundleSubsidies.putString("subsidiesBalance", subsidiesBalance);//带到下个页面
                //活动账号余额 点击事件
                Intent subsidies = new Intent(mContext, SubsidyTXActivity.class);
                subsidies.putExtras(bundleSubsidies);
                startActivityForResult(subsidies, Constant.RESULTCODE_100);
                break;
            case R.id.btn_exit:
                showExitDialog();
                break;
            case R.id.iv_prompt://温馨提示
                showTips();
                break;
            case R.id.hiv_device://机具申请
                //活动账号余额 点击事件
                Intent applyfor = new Intent(mContext, ApplyforDevicesActivity.class);
                startActivityForResult(applyfor, Constant.RESULTCODE_100);
//                ScreenSwitch.switchActivity(mContext, ApplyforDevicesActivity.class, null, Constant.RESULTCODE_100);
                break;
            case R.id.alert_cjtincome://超级推收益查询
                ScreenSwitch.switchActivity(mContext, CjtInComeActivity.class, null, 0);
                break;
        }
    }

    private CustomDialog exitDialog;
    private CustomDialog tipDialog;//温馨提示语提示框

    private void showExitDialog() {
        if (exitDialog == null) {

            exitDialog = DialogUtil.getDoubleCustomDialog(mContext, "温馨提醒", "您确定要退出吗？",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            UserInfo.removeUserInfo();
                            android.os.Process.killProcess(android.os.Process.myPid());
                            System.exit(0);
                            getActivity().finish();
                        }
                    });
        }
        if (!exitDialog.isShowing()) {

            exitDialog.show();
        }
    }

    /**
     * 显示温馨提示语
     */
    private void showTips() {
        if (tipDialog == null) {
            tipDialog = DialogUtil.getSingleCustomDialog(mContext, "温馨提醒", "当天的分润，为保障数据的完整，\n在第二个工作日核算后自动入账户余额.", "确  定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tipDialog.cancel();
                }
            });
        }
        if (mContext != null && !isDetached() && !tipDialog.isShowing()) {
            tipDialog.show();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //提现成功回来需要刷新余额 --zw 2017-5-8 15:57:32
        if (Constant.RESULTCODE_100 == requestCode && RESULT_OK == resultCode) {
            agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACCOUNTSUBJECTNO);
            //add by zhuangzeqin 2017年8月10日14:44:57 待处理的机具申请记录统计
            getCountTerminalApplyRecordInfo();
            //一级代理商才有活动补贴账户余额
//            if ("1".equals(UserInfo.getUserInfo2SP().getAgentLevel()))
            agentAccountBalanceRequestAPI.getAgentAccountBalanceInfo(SubjectNoTypeDef.ACTIVITYSUBJECTNO);
        }
    }

    @Override
    public void onResume() {
        if (MyApplication.getInstance().hasNews) {
            titleBar.setRightResource(R.drawable.icon_new_message);
        } else {
            titleBar.setRightResource(R.drawable.icon_message);
        }

        super.onResume();
    }

    public <T extends View> T getViewById(int id) {
        View view = this.view.findViewById(id);
        return (T) view;
    }

}
